package com.github.postsanf.yinian.activity;

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.HuoDongChartAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNChart;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class TimeLineStatusFristPaiHangActivity extends BaseActivity implements View.OnClickListener {
    private HashMap<Integer, String> rewardtips = new HashMap<>();
    private SimpleDraweeView paihangbang_pic;
    private YNAlbum curAlbum;
    private RecyclerView rv_members;
    private HuoDongChartAdapter mAdapter;
    private List<YNChart> mMemberDatas = new ArrayList<>();
    private SimpleDraweeView paihangbang_meavatar;
    private TextView paihangbang_mename;
    private TextView rl_item_album_num;
    private TextView paihangbang_rank;
    private String Bannerpurl="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline_topstatuspaihang);
        curAlbum = (YNAlbum) getIntent().getSerializableExtra("StatusFrist");
        Bannerpurl = curAlbum.getBannerPic();
        if (!Bannerpurl.contains("http")) {
            Bannerpurl = "http://" + Bannerpurl;
        }
        rewardtips.put(8, "礼品");
        rewardtips.put(28, "礼品");
        rewardtips.put(48, "礼品");
        rewardtips.put(68, "礼品");
        initView();
        noticePaihangServiceInit();
        RecyclerViewHeader headview = RecyclerViewHeader.fromXml(this, R.layout.activity_timeline_topstatuspaihang_top);
        paihangbang_pic = (SimpleDraweeView) headview.findViewById(R.id.paihangbang_pic);
        ImageOptHelper.showFrescoBlur(Uri.parse(Bannerpurl), paihangbang_pic, TimeLineStatusFristPaiHangActivity.this);
        headview.attachTo(rv_members);
    }

    private void initView() {
        findViewById(R.id.top_back).setOnClickListener(this);
        findViewById(R.id.top_back_time).setOnClickListener(this);
        rv_members = (RecyclerView) findViewById(R.id.rv_members);
        rv_members.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new HuoDongChartAdapter(this, mMemberDatas, YNSingleton.getInstance().getCurAlbum(), false, application.getCurID() + "");
        rv_members.setAdapter(mAdapter);
        rv_members.setHasFixedSize(true);
        paihangbang_meavatar = (SimpleDraweeView) findViewById(R.id.paihangbang_meavatar);
        paihangbang_mename = (TextView) findViewById(R.id.paihangbang_mename);
        rl_item_album_num = (TextView) findViewById(R.id.rl_item_album_num);
        paihangbang_rank = (TextView) findViewById(R.id.paihangbang_rank);
    }


    private void noticePaihangServiceInit() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(curAlbum.getGroupid()));
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/activity/ShowChart")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "paihang===>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optInt("code") == 0) {
                                JSONArray totalarray = jsonObject.optJSONArray("data").optJSONObject(0).optJSONArray("totalChart");
                                for (int i = 0; i < totalarray.length(); i++) {
                                    YNChart ynChart = new YNChart();
                                    ynChart.setUpic(totalarray.optJSONObject(i).optString("upic"));
                                    ynChart.setNum(totalarray.optJSONObject(i).optInt("num"));
                                    ynChart.setRank(totalarray.optJSONObject(i).optString("rank"));
                                    ynChart.setUserid(totalarray.optJSONObject(i).optInt("userid"));
                                    ynChart.setUnickname(totalarray.optJSONObject(i).optString("unickname"));
                                    mMemberDatas.add(ynChart);
                                }
                                mAdapter.notifyDataSetChanged();
                                int num = jsonObject.optJSONArray("data").optJSONObject(0).optJSONArray("personalChart").optJSONObject(0).optInt("num");
                                String rank = jsonObject.optJSONArray("data").optJSONObject(0).optJSONArray("personalChart").optJSONObject(0).optString("rank");
                                String name = jsonObject.optJSONArray("data").optJSONObject(0).optJSONArray("personalChart").optJSONObject(0).optString("unickname");
                                String pic = jsonObject.optJSONArray("data").optJSONObject(0).optJSONArray("personalChart").optJSONObject(0).optString("upic");
                                paihangbang_mename.setText(name);
                                rl_item_album_num.setText(String.valueOf(num));
                                String avatarPaths = YNUrlHelper.getAvatarUrl(TimeLineStatusFristPaiHangActivity.this, pic);
                                ImageOptHelper.showFrescoAvatar(Uri.parse(avatarPaths), paihangbang_meavatar, TimeLineStatusFristPaiHangActivity.this);
                                if (!rank.equals("未进入")) {
                                    String mc = "第" + rank + "名";
                                    Spannable WordtoSpan = new SpannableString(mc);
                                    WordtoSpan.setSpan(new TextAppearanceSpan(TimeLineStatusFristPaiHangActivity.this, R.style.item_paihang_text_style1), 0, 1,
                                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    WordtoSpan.setSpan(new TextAppearanceSpan(TimeLineStatusFristPaiHangActivity.this, R.style.item_paihang_text_style2), 1, rank.length() + 1,
                                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    WordtoSpan.setSpan(new TextAppearanceSpan(TimeLineStatusFristPaiHangActivity.this, R.style.item_paihang_text_style1), rank.length() + 1, mc.length(),
                                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    paihangbang_rank.setText(WordtoSpan);
                                } else {
                                    paihangbang_rank.setText(rank);
                                }
                                Iterator iter = rewardtips.entrySet().iterator();
                                while (iter.hasNext()) {
                                    Map.Entry entry = (Map.Entry) iter.next();
                                    int key = (Integer) entry.getKey();
                                    if (key == num) {
                                        String tt = "恭喜你！收获" + key + "个赞，获得了" + entry.getValue() + "添加小忆（微信号：yinianniubi）领取。";
                                        if (!SpUtils.getBoolean(TimeLineStatusFristPaiHangActivity.this, String.valueOf(application.getCurID()) + ":" + key))
                                            showRewardTip(tt);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void showRewardTip(String contentstr) {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_tip_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText(contentstr);
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("知道了");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_back:
            case R.id.top_back_time:
                finish();
                break;
        }
    }
}
